

using BlogApp.Domain;
using BlogApp.Dto;
using BlogApp.Repository;
using Microsoft.AspNetCore.Mvc;

namespace BlogApp.Controllers;

[ApiController]
[Route("api/[controller]")]
public class BlogsController : ControllerBase
{
    private readonly IRepository<Blog> _blogRep;
    public BlogsController(IRepository<Blog> blogRep)
    {
        _blogRep = blogRep;
    }

    [HttpGet]
    public async Task<IActionResult> Get()
    {
        var list = await _blogRep.GetAllAsync();
        return Ok(new { Code = 1000, Msg = "获取列表成功", Data = list });
    }

    [HttpPost]
    public async Task<IActionResult> Post(BlogCreateDto blogCreateDto)
    {
        var blog = new Blog { BlogName = blogCreateDto.BlogName, BlogAuthor = blogCreateDto.BlogAuthor };
        await _blogRep.CreateAsync(blog);
        return Ok(new { Code = 1000, Msg = "创建成功", Data = blog });

    }

    [HttpPut("{id}")]
    public async Task<IActionResult> Put(int id, BlogCreateDto blogCreateDto)
    {
        var blog = await _blogRep.GetByIdAsync(id);
        if (blog == null)
        {
            return Ok(new { Code = 1004, Msg = "未查询到", Data = "" });
        }
        blog.BlogName = blogCreateDto.BlogName;
        blog.BlogAuthor = blogCreateDto.BlogAuthor;
        await _blogRep.UpdateAsync(blog);
        return Ok(new { Code = 1000, Msg = "修改成功", Data = blog });

    }  

    [HttpDelete("{id}")]

    public async Task<IActionResult> Del(int id)
    {
        var blog = await _blogRep.GetByIdAsync(id);
        if (blog == null)
        {
            return Ok(new { Code = 1004, Msg = "未查询到", Data = "" });
        }

        await _blogRep.DeleteAsync(blog);
        return Ok(new { Code = 1000, Msg = "删除成功", Data = blog });

    } 
}